package com.mission.game.creategame;

import java.util.ArrayList;
import java.util.Collection;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mission.game.R;
import com.mission.game.components.RemoveAdapter;
import com.mission.game.utils.Game;
import com.mission.game.utils.Mission;
import com.mission.game.utils.Task;

public class CreateMissionScreen extends Activity {

	private Game _game;
	private Mission _mission;
	private ArrayList<String> _taskNames;
	private Collection<String> _missionNames = new ArrayList<String>();
	private EditText _missionNameView;
	private EditText _missionDescriptionView;
	private Task _sentTask;

	private final String NAME_EXISTS = " as a mission name already exists, please choose another.";
	private static final String NAME_REQUIRED = "Mission name is required, fill it in to continue.";
	protected static final int CREATE_TASK = 5;
	protected static final int EDIT_TASK = 6;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_new_mission);

		_missionNameView = (EditText) findViewById(R.id.mission_name_input);
		_missionDescriptionView = (EditText) findViewById(R.id.mission_description_input);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			if (extras.containsKey("game")) {
				_game = (Game) extras.getSerializable("game");
				_missionNames = _game.getMissionNames();
			}
			if (extras.containsKey("mission")) {
				_mission = (Mission) extras.getSerializable("mission");
				setFields();
			} else {
				_mission = new Mission(_game);
			}
		}

		setTasks();
	}

	private void setFields() {
		_missionNameView.setText(_mission.getName());
		_missionDescriptionView.setText(_mission.getDescription());
	}

	private void setTasks() {
		// Set current score
		((TextView) findViewById(R.id.current_mission_score)).setText(Integer
				.toString(_mission.getScore()));
		// Set chosen tasks list
		ListView tasksLv = (ListView) findViewById(R.id.chosen_tasks_list);
		_taskNames = _mission.getTaskNames();
		if (_taskNames.size() == 0)
			hideNext();
		else
			showNext();
		RemoveAdapter taskAdapter = new RemoveAdapter(this,
				R.layout.removable_list_item, _taskNames);
		tasksLv.setAdapter(taskAdapter);
		tasksLv.setTextFilterEnabled(true);
		tasksLv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				_sentTask = _mission.getTasks().get(position);
				Intent i = new Intent(getApplicationContext(), _sentTask
						.getCreateClass());
				i.putExtra("task", _sentTask).putExtra("tasklist", _taskNames);
				_mission.removeTask(_sentTask.getName());
				startActivityForResult(i, EDIT_TASK);
			}
		});
	}
	
	private void hideNext() {
		//		_missionNames.add(NO_MISSION_STRING);
		findViewById(R.id.tasks_header).setVisibility(View.INVISIBLE);
		findViewById(R.id.create_game_next_button_3).setVisibility(View.INVISIBLE);
	}

	private void showNext() {
		findViewById(R.id.tasks_header).setVisibility(View.VISIBLE);
		findViewById(R.id.create_game_next_button_3).setVisibility(View.VISIBLE);		
	}


	public void backToMissionControl(View v) {
		String name = _missionNameView.getText().toString();
		if (name.isEmpty()) {
			Toast.makeText(getApplicationContext(), NAME_REQUIRED,
					Toast.LENGTH_LONG).show();
			return;
		} else if (!_mission.getName().equals(name)
				&& _missionNames.contains(name)) {
			Toast.makeText(getApplicationContext(), name + NAME_EXISTS,
					Toast.LENGTH_LONG).show();
			return;
		}
		_mission.setName(name);
		_mission.setDescription(_missionDescriptionView.getText().toString());
		getIntent().putExtra("mission", _mission);
		setResult(Activity.RESULT_OK, getIntent());
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) { // Back key pressed
			getIntent().putExtra("mission", _mission);
			setResult(Activity.RESULT_OK, getIntent());
		}
		return super.onKeyDown(keyCode, event);
	}

	public void onAddTaskButtonClicked(View v) {
		Intent i = new Intent(getApplicationContext(), CreateTaskScreen.class);
		i.putExtra("tasklist", _taskNames);
		startActivityForResult(i, CREATE_TASK);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setTasks();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CREATE_TASK:
		case EDIT_TASK:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				Task task = (Task) data.getExtras().get("task");
				if (!task.getName().isEmpty()) {
					if (!task.hasMission()) {
						task.setMission(_mission);
					}
					if (_mission.hasTask(task)) {
						_mission.updateTask(task);
					} else {
						_mission.addTask(task);
					}
				}
			} else if (resultCode == RESULT_CANCELED && _sentTask != null) {
				_mission.addTask(_sentTask);
			}
			break;
		default:
			break;
		}
	}

	public void removeTaskItem(int position) {
		final String clickedTask = _taskNames.get(position);
		new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Remove Item")
				.setMessage(
						"Are you sure you want to remove " + clickedTask
								+ " from the list?")
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								_missionNames.remove(clickedTask);
								_mission.removeTask(clickedTask);
								setTasks();
							}

						}).setNegativeButton("No", null).show();
	}
}
